package com.dengqi.mymodule.activity.layoutinflater;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.dengqi.mymodule.BaseActivity;
import com.dengqi.mymodule.R;

import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.view.LayoutInflaterCompat;

/**
 * https://mp.weixin.qq.com/s/gSMXJhfmQ4yAE7ikKRIb4g
 * Created by dell on 2018/12/3
 */
public class LayoutInflaterActivity extends BaseActivity {

    private String TAG = "LayoutInflaterActivity";
    public static Typeface typeface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (typeface == null){
            typeface = Typeface.createFromAsset(getAssets(), "abc.ttf");
        }
        LayoutInflaterCompat.setFactory2(LayoutInflater.from(this), new LayoutInflater.Factory2() {
            //'这个方法是Factory2里面定义的方法'
            @Override
            public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
//                Log.e(TAG, "parent:" + parent + ",name = " + name);
//                int n = attrs.getAttributeCount();
//                for (int i = 0; i < n; i++) {
//                    Log.e(TAG, attrs.getAttributeName(i) + " , " + attrs.getAttributeValue(i));
//                }
                //TextView，ImageView改为Button
                if("TextView".equals(name) || "ImageView".equals(name)){
                    name = "Button";
                }

                //'我们只是更换了参数，但最终实例化View的逻辑还是交给了AppCompatDelegateImpl'
                AppCompatDelegate delegate = getDelegate();
                View view = delegate.createView(parent, name, context, attrs);

                //全局替换字体等属性、动态换肤功能、无需编写shape、selector，直接在xml设置值
                if ( view!= null && (view instanceof Button)){
                    ((Button) view).setTypeface(typeface);
                }

                return view;
            }

            //'这个方法是Factory接口里面的，因为Factory2是继承Factory的'
            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                return null;
            }
        });


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layoutinflater);
    }

    public void onBtn1(View view){
        startActivity(new Intent(this, InflaterCustomActivity.class));
    }
}
